package com.lotus.tep.event;

import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserAdapter;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserNavigationEvent;
import com.lotus.tep.constant.UrlConstant;
import com.lotus.tep.util.SpeechUtil;
import javax.swing.SwingUtilities;

public abstract class AbstractWindowHandler extends WebBrowserAdapter {

	private JWebBrowser jWebBrowser_;

	protected final JWebBrowser getJWebBrowser() {
		return jWebBrowser_;
	}

	protected final void setWebBrowserToNull() {
		jWebBrowser_ = null;
	}

	protected final boolean isWebBrowserNull() {
		return null == jWebBrowser_;
	}

	protected abstract String getUrlPrefix();

	private void setJWebBrowser(JWebBrowser webBrowser) {
		jWebBrowser_ = null == webBrowser ? jWebBrowser_ : webBrowser;
	}

	protected class SpeakerEmbeder implements Runnable {

		private String text;
		private JWebBrowser jWebBrowser_;

		public SpeakerEmbeder(JWebBrowser jWebBrowser_) {
			this.jWebBrowser_ = jWebBrowser_;
		}

		@Override
		public void run() {
			try {
				text = (String) jWebBrowser_.executeJavascriptWithResult(getScriptToExtractSpeechText());
				if (!isEmptyText()) {
					SpeechUtil.speakIt(text);
				}
			} catch (ClassCastException cce) {
				System.err.println(cce);
			}
		}

		private boolean isEmptyText() {
			return null == text || text.trim().isEmpty();
		}
	}

	@Override
	public void locationChanged(WebBrowserNavigationEvent e) {
		String url = e.getNewResourceLocation();
		boolean starts = url.startsWith(getUrlPrefix());
		boolean isNull = isWebBrowserNull();
//		System.out.printf("starts=%s, isNull=%s\n", starts, isNull);
		if (starts && isNull) {
			setJWebBrowser(e.getWebBrowser());
			SwingUtilities.invokeLater(new SpeakerEmbeder(e.getWebBrowser()));
		}
		setWebBrowserToNull();
	}

	protected abstract String getScriptToEmbedSpeakers();

	protected String getScriptToExtractSpeechText() {
		StringBuilder toReturn = new StringBuilder();
		toReturn.append("var font = document.getElementsByTagName('font')[0];");
		toReturn.append("var spans = font.childNodes[0].getElementsByTagName('span');");
		toReturn.append("var cont = [];");
		toReturn.append("var i = 0, len = spans.length;");
		toReturn.append("while(i < len){");
		toReturn.append("cont[i] = spans[i].textContent || spans[i].innerText;");
		toReturn.append("i ++;");
		toReturn.append("}");
		toReturn.append("return cont.toString();");
		return toReturn.toString();
	}

	protected final String getJQueryUrl() {
		return UrlConstant.JQUERY_SCRIPT_URL;
	}
}
